<?php

namespace common\components;

use Yii;
use yii\helpers\Url;
use yii\rbac\ManagerInterface;
use yii\web\Controller;
use yii\web\Response;

/**
 * @property ManagerInterface|RbacPhpManager authManager
 */
class WebController extends Controller
{

    const FLASH_MSG_TYPE_SUCCESS = 'success';
    const FLASH_MSG_TYPE_ERROR = 'error';
    const FLASH_MSG_TYPE_DANGER = 'danger';
    const FLASH_MSG_TYPE_INFO = 'info';
    const FLASH_MSG_TYPE_WARING = 'warning';

    /**
     * @var mixed
     */
    public $error = null;

    /**
     * @return ManagerInterface|RbacPhpManager
     */
    public function getAuthManager()
    {
        return Yii::$app->authManager;
    }

    /**
     * 跳转会上一页
     *
     * @return Response
     */
    public function back()
    {
        return $this->redirect(Yii::$app->request->referrer);
    }

    /**
     * Set return url for module in sessions
     *
     * @param mixed $url if not set, returnUrl will be current page
     */
    public function setReturnUrl($url = null)
    {
        Yii::$app->getSession()->set($this->module->id . '_return', $url ? Url::to($url) : Url::current());
    }

    /**
     * Get return url for module from session
     *
     * @param mixed $defaultUrl if return url not found in sessions
     * @return mixed
     */
    public function getReturnUrl($defaultUrl = null)
    {
        return Yii::$app->getSession()->get($this->module->id . '_return', $defaultUrl
            ? Url::to($defaultUrl)
            : Url::toRoute($this->module->id));
    }

    /**
     * Write in sessions alert messages
     *
     * @param string $type    error or success
     * @param string $message alert body
     * @param null   $url
     * @return string
     */
    public function flash($type, $message, $url = null)
    {
        Yii::$app->getSession()->setFlash($type == self::FLASH_MSG_TYPE_ERROR ? self::FLASH_MSG_TYPE_DANGER : $type, $message);

        if ($url !== null)
        {
            $this->redirect($url);
        }
        return '';
    }

    /**
     * 根据请求类型来决定返回数据（是否是ajax）
     *
     * @param string $success
     * @param bool   $back go back or refresh
     * @return mixed $result array if request is ajax.
     */
    public function formatResponse($success = '', $back = true)
    {
        if (Yii::$app->request->isAjax)
        {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($this->error)
            {
                return ['result' => 'error', 'error' => $this->error];
            }
            else
            {
                $response = ['result' => 'success'];
                if ($success)
                {
                    if (is_array($success))
                    {
                        $response = array_merge(['result' => 'success'], $success);
                    }
                    else
                    {
                        $response = array_merge(['result' => 'success'], ['message' => $success]);
                    }
                }
                return $response;
            }
        }
        else
        {
            if ($this->error)
            {
                $this->flash('error', $this->error);
            }
            else
            {
                if (is_array($success) && isset($success['message']))
                {
                    $this->flash('success', $success['message']);
                }
                elseif (is_string($success))
                {
                    $this->flash('success', $success);
                }
            }
            return $back ? $this->back() : $this->refresh();
        }
    }
}
